/*
 * socket.cpp
 *
 *  Created on: 14/11/2012
 *      Author: leonardo
 */

#include "socket.h"

Socket::Socket() {
	this->caller_socket = 0;
	this->port = 0;
	this->serverIP = "0.0.0.0";
}

Socket::Socket(const char *ip, const int port) {
	this->caller_socket = 0;
	this->serverIP = ip;
	this->port = port;

	// Creación del socket
	if ((caller_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		cout << "Error al crear el socket!" << endl;
	}

	// Completo la estructura de datos
	listen_address.sin_family = AF_INET;
	listen_address.sin_port = htons(this->port);
	listen_address.sin_addr.s_addr = inet_addr(this->serverIP.c_str());
	bzero(&(listen_address.sin_zero), 8);
}

Socket::Socket(const string & ip, const int port) {
	this->caller_socket = 0;
	this->serverIP = ip;
	this->port = port;

	// Completo la estructura de datos
	listen_address.sin_family = AF_INET;
	listen_address.sin_port = htons(this->port);
	listen_address.sin_addr.s_addr = inet_addr(this->serverIP.c_str());
	bzero(&(listen_address.sin_zero), 8);
}

Socket::Socket(const Socket &rObj) {
	port = rObj.port;
	serverIP = rObj.serverIP;
	caller_socket = rObj.caller_socket;
	listen_address = rObj.listen_address;
}

Socket& Socket::operator =(const Socket &rObj) {
	port = rObj.port;
	serverIP = rObj.serverIP;
	caller_socket = rObj.caller_socket;
	listen_address = rObj.listen_address;

	return *this;
}

Socket::~Socket() {}

bool Socket::createSocket(void) {
	if ((caller_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		return false;
	}
	return true;
}

bool Socket::createSocket(const string & ip, const int port) {
	this->caller_socket = 0;
	this->serverIP = ip;
	this->port = port;

	// Completo la estructura de datos
	listen_address.sin_family = AF_INET;
	listen_address.sin_port = htons(this->port);
	listen_address.sin_addr.s_addr = inet_addr(this->serverIP.c_str());
	bzero(&(listen_address.sin_zero), 8);

	if ((caller_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		return false;
	}
	return true;
}

bool Socket::createSocket(const char *ip, const int port) {
	this->caller_socket = 0;
	this->serverIP = ip;
	this->port = port;

	// Completo la estructura de datos
	listen_address.sin_family = AF_INET;
	listen_address.sin_port = htons(this->port);
	listen_address.sin_addr.s_addr = inet_addr(this->serverIP.c_str());
	bzero(&(listen_address.sin_zero), 8);

	if ((caller_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		return false;
	}
	return true;
}


bool Socket::connectToHost() {
	if (connect(caller_socket, (struct sockaddr*) &listen_address, sizeof(struct sockaddr)) < 0) {
		return false;
	}
	return true;
}

void Socket::closeSocket() {
	close(this->caller_socket);
}

int Socket::sendMessage(const void *buffer, size_t buffer_size, int flags) {
	return send(this->caller_socket, buffer, buffer_size, flags);
}

int Socket::receiveMessage(void *buffer, size_t buffer_size, int flags) {
	return recv(this->caller_socket, buffer, buffer_size, flags);
}
